package com.ys.service.mall.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bo.vo.R;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.mall.TmCate;
import com.ys.mapper.mall.MallMapper;
import com.ys.mapper.mall.TmCateMapper;
import com.ys.service.mall.TmCateService;

@Service("tmCateService")
public class TmCateServiceImpl implements TmCateService {

	@Autowired
	private MallMapper mallMapper;
	@Autowired
	private TmCateMapper tmCateMapper;


	@Override

	public R add(Map<String, Object> params) {
		
		// 获取排序
		Integer sortNo = mallMapper.getNextSortNoOfTmCate();
		
		TmCate entity = JSON.parseObject(JSON.toJSONString(params), TmCate.class);
		entity.setSortNo(sortNo);
		tmCateMapper.insert(entity);
		
		
		return R.ok(AddDto.closeAndReload());
	}
	
	@Override
	public R edit(Map<String, Object> params) {

		TmCate entity = JSON.parseObject(JSON.toJSONString(params), TmCate.class);
		tmCateMapper.update(entity);
		
		return R.ok(EditDto.closeAndReload());
	}

	@Override
	@Transactional
	public R moveTop(Long id) throws Exception {
		mallMapper.moveTopOfTmCate(id);
		return R.ok();
	}

	@Override
	@Transactional
	public R resort(String rows) {
		JSONArray JA = JSON.parseArray(rows);
		
		for (int i = 0; i < JA.size(); i++) {
			JSONObject JO = JA.getJSONObject(i);
			Long id = JO.getLong("id");
			Integer sortNo = i + 1;
			mallMapper.updateTmCateOfSortNo(id, sortNo);
		}
		return R.ok();
	}
}
